<template>
  <a-modal title="社矫对象选择" v-model="open" @cancel="closeModel" @ok="ok" width="55%">
    <div style="display: flex">
      <a-col :xxl="4" :lg="4" :sm="4">
        <a-tabs :activeKey="tabKey" tab-position="left" @change="tabChange">
          <a-tab-pane key="person" tab="人员"> </a-tab-pane>
          <a-tab-pane key="group" tab="分组" force-render> </a-tab-pane>
        </a-tabs>
      </a-col>
      <a-col :xxl="12" :lg="12" :sm="12">
        <div style="width: 100%">
          <!--<a-input-search style="margin-bottom: 3px" placeholder="请搜索" />-->
          <!-- 分组使用的是树选择器 -->
          <a-tree-select
            v-if="tabKey == 'group'"
            style="width: 100%"
            tree-checkable
            show-search
            dropdown-match-select-width
            tree-node-filter-prop="title"
            v-model="checkedKeys"
            :multiple="true"
            :show-checked-strategy="SHOW_PARENT"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="treeData"
            :default-value="defaultCheckedKeys"
            showArrow
            @change="check"
          >
          </a-tree-select>
          <div v-else style="width: 100%">
            <a-tree-select
              style="width: 100%"
              tree-checkable
              show-search
              dropdown-match-select-width
              tree-node-filter-prop="title"
              v-model="checkedKeys"
              :multiple="true"
              :show-checked-strategy="SHOW_PARENT"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="treeData"
              :default-value="defaultCheckedKeys"
              showArrow
              @change="check"
            >
            </a-tree-select>
          </div>
        </div>
      </a-col>
      <a-col :xxl="8" :lg="8" :sm="8">
        <a-card style="margin-left: 20px">
          已选人员： {{ checkedPersonIds.length }}
          <a-list :data-source="checkedPerson" :style="{ maxHeight: '400px', overflow: 'auto' }">
            <a-list-item slot="renderItem" slot-scope="item">
              {{ item.title }}
            </a-list-item>
          </a-list>
          已选分组： {{ checkedGroupIds.length }}
          <a-list :data-source="checkedGroup" :style="{ maxHeight: '400px', overflow: 'auto' }">
            <a-list-item slot="renderItem" slot-scope="item">
              {{ item.title }}
            </a-list-item>
          </a-list>
        </a-card>
      </a-col>
    </div>
  </a-modal>
</template>
<script>
import { findAllPerson } from '@/api/correction/crc_person'
import { groupList } from '@/api/correction/crc_group'
import { personsByGroupId } from '@/api/correction/crc_group_person'
import { getPersonList } from '@/api/correction/crc_person'
import { getPersonIdsByRuleId } from '@/api/correction/crw_rule_person'
import { getGroupIdsByRuleId } from '@/api/correction/crw_rule_group'
import { TreeSelect } from 'ant-design-vue'
import { Tp_crc_ctrlValue } from '@/enumeration/correction/Tp_crc_ctrl'
import { Decrypt } from '@/enumeration/SM.js'

const SHOW_PARENT = TreeSelect.SHOW_PARENT
export default {
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    ruleId: {
      type: String,
      default: undefined,
    },
  },
  watch: {
    visible() {
      this.open = this.visible
    },
  },
  computed: {
    SHOW_PARENT() {
      return SHOW_PARENT
    },
    checkedPerson() {
      return this.personList.filter((item) => this.checkedPersonIds.includes(item.key))
    },
    checkedGroup() {
      return this.groupList.filter((item) => this.checkedGroupIds.includes(item.key))
    },
  },
  data() {
    return {
      open: false,
      tabKey: 'person',
      columns: [
        {
          title: '名称',
          dataIndex: 'name',
          key: 'name',
          align: 'left',
        },
      ],
      treeData: [],
      personList: [],
      groupList: [],
      groupPersonList: [],
      checkedKeys: [],
      defaultCheckedKeys: [],
      checkedPersonIds: [],
      checkedGroupIds: [],
      originalPersonIds: [],
      originalGroupIds: [],
      activeKey: 0,
    }
  },
  methods: {
    personTypeClassify() {
      const _this = this
      const p = new Promise(function (resolve, reject) {
        resolve()
        // 按照人员类型进行分类
        if (_this.treeData) {
          const personLevel1 = []
          const personLevel2 = []
          const personLevel3 = []
          for (const person of _this.treeData) {
            if (person.type === Tp_crc_ctrlValue.A) {
              personLevel1.push(person)
            } else if (person.type === Tp_crc_ctrlValue.B) {
              personLevel2.push(person)
            } else if (person.type === Tp_crc_ctrlValue.C) {
              personLevel3.push(person)
            }
          }
          // 拼接为树形结构
          const node1 = {
            title: '一类人员',
            value: 'first',
            key: 'first',
            children: personLevel1,
          }
          const node2 = {
            title: '二类人员',
            value: 'second',
            key: 'second',
            children: personLevel2,
          }
          const node3 = {
            title: '三类人员',
            value: 'third',
            key: 'third',
            children: personLevel3,
          }
          _this.treeData = []
          _this.treeData.push(node1)
          _this.treeData.push(node2)
          _this.treeData.push(node3)
        }
      })
      return p
    },

    tabChange(tabKey) {
      this.tabKey = tabKey
      if (tabKey === 'person') {
        this.treeData = this.personList
        // 按照人员进行分类
        this.personTypeClassify().then(() => {
          this.checkedKeys = this.checkedPersonIds
        })
      } else if (tabKey === 'group') {
        this.treeData = this.groupList
        this.checkedKeys = this.checkedGroupIds
      } else {
        this.treeData = []
      }
      this.treeData.forEach((item) => {
        if (tabKey === 'group') {
          item.selectable = true
          item.checkable = true
          item.children = []
          item.value = item.key
        } else {
          item.selectable = false
          item.checkable = false
          item.value = item.key
          if (item.children && item.children.length > 0) {
            item.children.forEach((child) => {
              child.selectable = true
              child.checkable = true
              child.children = []
              child.value = child.key
            })
          }
        }
      })
      console.log('treeData', this.treeData)
    },
    check(selectedKeys) {
      console.log('selectedKeys', selectedKeys)
      if (this.tabKey === 'person') {
        this.checkedPersonIds = selectedKeys
        this.checkedKeys = this.checkedPersonIds
      } else if (this.tabKey === 'group') {
        this.checkedGroupIds = selectedKeys
        this.checkedKeys = this.checkedGroupIds
      }
    },
    async ok() {
      let personNames = []
      if (this.checkedGroupIds.length > 0) {
        const { code, data } = await personsByGroupId(this.checkedGroupIds.join(','))
        if (code !== 0) {
          this.$message.error('根据分组获取人员信息失败')
          return
        }
        Object.values(data).forEach((value) => {
          if (value.length > 0) {
            value.forEach((item) => personNames.push(item.name))
          }
        })
      }
      this.checkedPerson.forEach((item) => personNames.push(item.title))

      personNames = [...new Set(personNames)].sort((a, b) => a.localeCompare(b, 'zh-CN'))
      let pernames
      if (personNames.length > 3) {
        pernames = personNames.slice(0, 3).join('，') + '等'
      } else {
        pernames = personNames.join('，')
      }
      this.$emit('ok', this.checkedPersonIds, this.checkedGroupIds, pernames)
    },
    closeModel() {
      this.$emit('close')
    },
    async loadPerson() {
      const { code, data } = await getPersonList()
      if (code !== 0) {
        this.$message.error('获取社矫对象数据失败')
        return
      }
      if (data.length > 0) {
        this.personList = data.map((item) => {
          const obj = {}
          obj.key = item.id
          obj.title = Decrypt(item.name)
          obj.type = item.controltype
          return obj
        })
      }
    },
    async loadGroup() {
      const { code, data } = await groupList({ pageSize: 99999, f_deleted_op: 0 })
      if (code !== 0) {
        this.$message.error('获取社矫对象数据失败')
        return
      }
      if (data.records.length > 0) {
        this.groupList = data.records.map((item) => {
          const obj = {}
          obj.key = item.id
          obj.title = item.name
          return obj
        })
      }
    },
    setActiveKey(key) {
      this.activeKey = key
    },
  },
  async created() {
    await this.loadPerson()
    await this.loadGroup()
    console.log('人员信息', this.personList)
    console.log('分组信息', this.groupList)
    if (this.ruleId) {
      const personIdsResult = await getPersonIdsByRuleId(this.ruleId)
      if (personIdsResult.code !== 0) {
        this.$message.error('未获取到预警人员信息')
        return
      }
      this.originalPersonIds = personIdsResult.data

      const groupIdsResult = await getGroupIdsByRuleId(this.ruleId)
      if (groupIdsResult.code !== 0) {
        this.$message.error('未获取到预警人员分组信息')
        return
      }
      this.originalGroupIds = groupIdsResult.data
    }
    if (this.tabKey === 'person') {
      this.treeData = this.personList
      // 按照人员进行分类
      this.personTypeClassify().then(() => {
        this.checkedKeys = this.originalPersonIds
        this.defaultCheckedKeys = this.originalPersonIds
      })
    } else if (this.tabKey === 'group') {
      this.treeData = this.groupList
      this.checkedKeys = this.originalGroupIds
      this.defaultCheckedKeys = this.originalGroupIds
    }
    this.checkedPersonIds = this.originalPersonIds
    this.checkedGroupIds = this.originalGroupIds
    this.treeData.forEach((item) => {
      if (this.tabKey === 'group') {
        item.selectable = true
        item.checkable = true
        item.children = []
        item.value = item.key
      } else {
        item.selectable = false
        item.checkable = false
        item.value = item.key
        if (item.children && item.children.length > 0) {
          item.children.forEach((child) => {
            child.selectable = true
            child.checkable = true
            child.children = []
            child.value = child.key
          })
        }
      }
    })
    console.log('created.treeData', this.treeData)
  },
}
</script>

<style lang="less" scoped>
::v-deep .ant-select-selection {
  min-height: 44px;
  background: #ffffff;
  border: 1px solid #e9e9e9;
  border-radius: 2px;
}
::v-deep .ant-select-selection__placeholder {
  height: 44px;
  margin-top: -5px;
}
::v-deep .ant-select-arrow {
  margin-top: -5px;
  color: rgba(0, 0, 0, 0.25);
  font-size: 18px;
}

.person-type-div {
  display: flex;
  justify-content: start;
  align-items: center;
}
.person-noselect-style {
  font-size: 16px;
  font-family: PingFang SC;
  font-weight: 500;
  color: #666666;
  line-height: 7px;
  margin: 0px 15px 0px 15px;
}
.person-select-style {
  font-size: 16px;
  font-family: PingFang SC;
  font-weight: 500;
  color: #2c2c2c;
  line-height: 7px;
  margin: 0px 15px 0px 15px;
  font-weight: bold;
}
</style>
